import cv2 as cv
import matplotlib.pyplot as plt

plt.rcParams["font.sans-serif"] = ["SimSun"]

img = cv.imread(r"6\3.png", cv.IMREAD_GRAYSCALE)
_, img_binary = cv.threshold(img, 128, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
kernelSize = 130
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (kernelSize, kernelSize))
img_dilate = cv.dilate(img_binary, kernel, iterations=1)
img_erode = cv.erode(img_binary, kernel, iterations=1)
img_open = cv.morphologyEx(img_binary, cv.MORPH_OPEN, kernel)
img_close = cv.morphologyEx(img_binary, cv.MORPH_CLOSE, kernel)
plt.figure()
plt.subplot(151)
plt.axis("off")
plt.imshow(img_binary, cmap="gray")
plt.title("二值图像")
plt.subplot(152)
plt.axis("off")
plt.imshow(img_dilate, cmap="gray")
plt.title("膨胀运算结果")
plt.subplot(153)
plt.axis("off")
plt.imshow(img_erode, cmap="gray")
plt.title("腐蚀运算结果")
plt.subplot(154)
plt.axis("off")
plt.imshow(img_open, cmap="gray")
plt.title("开运算结果")
plt.subplot(155)
plt.axis("off")
plt.imshow(img_close, cmap="gray")
plt.title("闭运算结果")
plt.tight_layout()
plt.show()
